package dbUtils

import (
	"bufio"
	"encoding/json"
	"fmt"
	"gitee.com/lv_baobao/gcore/logHelper"
	"io"
	"os"
	"sync"
)

type DbParseHelper struct {
}

var dbParseHelperOnce sync.Once
var dbParseHelper *DbParseHelper

func NewDbParseHelper() *DbParseHelper {
	dbParseHelperOnce.Do(func() {
		dbParseHelper = &DbParseHelper{}
	})
	return dbParseHelper
}

func (d *DbParseHelper) ParseDbLog(fileName string) ([]*DbLogContent, error) {
	f, err := os.Open(fileName)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	buf := bufio.NewReader(f)
	var result []*DbLogContent
	for {
		bytes, err := buf.ReadBytes('\n')
		if err != nil {
			if err == io.EOF { //读取结束，会报EOF
				break
			}
			return nil, err
		}
		var logContent = &DbLogContent{}
		err = json.Unmarshal(bytes, logContent)
		if err != nil {
			logHelper.Error(err)
			fmt.Println(string(bytes))
			continue
		}
		result = append(result, logContent)
	}
	return result, nil
}
